package it.patamau.bukkit;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLConnection {
	
	private Connection _connection;
	
	public MySQLConnection(){
		//Register the JDBC driver for MySQL.
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		_connection = null;
	}
	
	public boolean connect(String url, String user, String password){
		try{
			_connection = DriverManager.getConnection(url,user, password);
			return true;
		}catch(SQLException e){
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean isConnected(){
		try {
			return _connection!=null&&!_connection.isClosed();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean execute(String sql){
		try{
			//Get a Statement object
			Statement stmt = _connection.createStatement();
			stmt.execute(sql);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public ResultSet executeResult(String sql){
		try{
			//Get a Statement object
			Statement stmt = _connection.createStatement();
			if(stmt.execute(sql)){
				return stmt.getResultSet();
			}else{
				return null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String args[]){
		//Define URL of database server for
		// database named mysql on the localhost
		// with the default port number 3306.
		String url = "jdbc:mysql://localhost:3306/mysql";
		String user = "root";
		String password = "";
		
		MySQLConnection dbman = new MySQLConnection();
		if(dbman.connect(url, user, password)){
			dbman.execute("SELECT * FROM dm_players");
		}

	}
}
